<template>
  <div class="doctor-list-container">
    <el-row :gutter="20">
      <el-col
          v-for="doctor in doctorList"
          :key="doctor.id"
          :xs="24"
          :sm="24"
          :md="12"
          :lg="8"
      >
        <el-card class="doctor-card" shadow="hover">
          <div class="card-content">
            <el-avatar :size="80" :src="doctor.avatar" class="doctor-avatar"/>
            <div class="doctor-info">
              <h3 class="name">{{ doctor.userRealName }}</h3>
              <p class="title">{{ doctor.title || '资深心理咨询师' }}</p>
              <p class="desc">{{ doctor.description || '专业领域：情感咨询、压力管理' }}</p>
            </div>
          </div>

          <div class="card-actions">
            <el-button
                type="primary"
                size="small"
                @click="handleConsult(doctor)"
            >
              立即咨询
            </el-button>
            <el-button
                type="success"
                size="small"
                @click="handleAppointment(doctor)"
            >
              预约咨询
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 聊天弹窗 -->
    <el-dialog
        v-model="chatDialogVisible"
        title="在线咨询"
        width="50%"
    >
      <div class="chat-container">
        <el-scrollbar ref="scrollbarRef" class="message-area" height="400px">
          <div
              v-for="(msg, index) in messages"
              :key="index"
              class="message-bubble"
              :class="{ 'user-message': msg.senderId === getUser().userInfo.id, }"
          >
            <div class="message-content">
              <p class="message-text">{{ msg.content }}</p>
              <span class="message-time">{{ formatTime(msg.createTime) }}</span>
            </div>
          </div>
        </el-scrollbar>

        <div class="input-area">
          <el-form>
            <el-input
                v-model="newMessage"
                placeholder="输入咨询内容..."
                type="textarea"
                :rows="3"
                resize="none"
            />
            <div class="send-button">
              <el-button type="primary" @click="sendMessageHandler">发送</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </el-dialog>

    <!-- 预约弹窗 -->
    <el-dialog
        v-model="appointDialogVisible"
        title="心理咨询预约"
        width="30%"
    >
      <el-form
          :model="appointForm"
          :rules="appointRules"
          label-width="100px"
          ref="appointFormRef"
      >
        <el-form-item label="预约时间" prop="appointTime">
          <el-date-picker
              v-model="appointForm.appointTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="appointDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitAppointment">
        确认预约
      </el-button>
    </span>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <div class="pagination-wrapper">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getDoctorPage} from '@/api/user'
import {faker} from '@faker-js/faker'
import dayjs from "dayjs";
import {getUser} from "@/store/userStore.js";
import {getConsultList, sendMessage} from "@/api/consult.js";
import {insertAppointment} from "@/api/appointment.js";

const router = useRouter()
const appointDialogVisible = ref(false)

// 获取滚动条实例
const scrollbarRef = ref(null);

// 医生列表数据
const doctorList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 聊天相关数据
const chatDialogVisible = ref(false)
const currentDoctor = ref(null)
const newMessage = ref('')
const messages = ref([])
let socket = null

// 初始化WebSocket
const initWebSocket = () => {
  if (process.env.NODE_ENV === 'development') {
    // 开发环境模拟消息
    messages.value = [
      {
        content: '您好，有什么可以帮助您的？',
        time: new Date(),
        isUser: false
      }
    ]
    return
  }

  const wsUrl = `ws://your-api-domain.com/ws/${currentDoctor.value.id}`
  socket = new WebSocket(wsUrl)

  socket.onmessage = (e) => {
    messages.value.push({
      content: e.data,
      time: new Date(),
      isUser: false
    })
  }
}

// 滚动到底部的函数
const scrollToBottom = () => {
  if (scrollbarRef.value) {
    scrollbarRef.value.scrollTop = scrollbarRef.value.scrollHeight;
  }
};

// 发送消息
const sendMessageHandler = async () => {
  if (!newMessage.value.trim()) return

  const message = {
    content: newMessage.value,
    time: new Date(),
    isUser: true
  }

  messages.value.push(message)

  // TODO: 发送消息到WebSocket
  await sendMessage({
    senderId: getUser().userInfo.id,
    receiverId: currentDoctor.value.id,
    content: newMessage.value,
    messageType: 0
  })
  newMessage.value = ''
  ElMessage.success('发送成功')

  const res = await getConsultList({senderId: getUser().userInfo.id, receiverId: currentDoctor.value.id})
  messages.value = res.data.reverse()
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY:MM:DD HH:mm:ss')
}

// 获取医生列表
const fetchDoctors = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      type: 1 // 筛选医生类型
    }
    // 开发环境使用模拟数据
    // if (process.env.NODE_ENV === 'development') {
    //   doctorList.value = Array.from({length: 10}, (_, i) => ({
    //     id: i + 1,
    //     userRealName: faker.person.fullName(),
    //     avatar: faker.image.avatar(),
    //     title: faker.helpers.arrayElement(['主任医师', '副主任医师', '心理咨询师']),
    //     description: faker.lorem.sentence(10)
    //   }))
    //   total.value = 100
    //   return;
    // }
    const res = await getDoctorPage(params)
    doctorList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取医生列表失败')
  }
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchDoctors()
}

// 立即咨询
const handleConsult = async (doctor) => {
  if (!checkAuth()) return
  chatDialogVisible.value = true
  currentDoctor.value = doctor
  // 初始化WebSocket连接
  // initWebSocket()
  const res = await getConsultList({senderId: getUser().userInfo.id, receiverId: doctor.id})
  messages.value = res.data.reverse()
  await nextTick(() => {
    scrollToBottom();
  })

}

// 预约咨询
const handleAppointment = async (doctor) => {
  if (!checkAuth()) return
  appointForm.doctorId = doctor.id
  appointDialogVisible.value = true
}

// 预约表单数据
const appointForm = reactive({
  userId: 0,
  doctorId: 0,
  appointTime: ''
})

// 表单验证规则
const appointRules = {
  appointTime: [
    {required: true, message: '请选择预约时间', trigger: 'blur'}
  ]
}

// 提交预约
const submitAppointment = () => {
  ElMessageBox.confirm('确认提交该预约申请吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      appointForm.userId = getUser().userInfo.id
      if (appointForm.appointTime === '') {
        ElMessage.error('请选择预约时间')
        return
      }
      // 这里调用预约接口
      await insertAppointment(appointForm)
      ElMessage.success('预约申请已提交')
      appointForm.appointTime = ''
      appointDialogVisible.value = false
    } catch (error) {
      ElMessage.error('预约提交失败')
    }
  })
}

// 权限检查
const checkAuth = () => {
  const userStore = getUser()
  if (!userStore?.isLogin) {
    ElMessage.warning('请先登录')
    router.push(`/login?redirect=${router.currentRoute.value.fullPath}`)
    return false
  }
  return true
}

onMounted(() => {
  fetchDoctors()
})
</script>

<style lang="scss" scoped>
.chat-container {
  padding: 10px;

  .message-area {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    margin-bottom: 15px;
    padding: 10px;

    .message-bubble {
      max-width: 90%;
      margin: 10px 0;
      display: flex;
      justify-content: flex-start;

      &.user-message {
        justify-content: flex-end;

        .message-content {
          background-color: #409eff;
          color: white;
        }
      }

      .message-content {
        background-color: #f5f7fa;
        border-radius: 12px;
        padding: 10px 15px;
        max-width: 100%;
        width: fit-content;

        .message-text {
          margin: 0;
          word-break: break-word;
        }

        .message-time {
          font-size: 12px;
          color: #909399;
          margin-top: 5px;
          display: block;
          text-align: right;
        }
      }
    }
  }

  .input-area {
    .send-button {
      margin-top: 10px;
      text-align: right;
    }

  }
}

.doctor-list-container {
  padding: 20px;

  .doctor-card {
    margin-bottom: 20px;
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-5px);
    }

    .card-content {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      .doctor-avatar {
        margin-right: 15px;
      }

      .doctor-info {
        flex: 1;

        .name {
          margin: 0 0 12px;
          font-size: 18px;
        }

        .title {
          margin: 0 0 8px;
          font-size: 14px;
        }

        .desc {
          font-size: 13px;
        }
      }

      .card-actions {
        margin-top: 15px;
      }
    }

    .card-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
